package com.example.init;

import cn.hutool.core.util.ReflectUtil;
import com.alibaba.druid.pool.DruidDataSource;
import com.example.util.ConfigUtil;
import lombok.extern.slf4j.Slf4j;
import org.sagacity.sqltoy.SqlToyContext;
import org.sagacity.sqltoy.dao.SqlToyLazyDao;
import org.sagacity.sqltoy.dao.impl.DefaultLazyDaoImpl;

import java.io.Serializable;

@Slf4j
public class MybatisDbUtil {
    private static SqlToyLazyDao dao;

    static {
        try {
            SqltoyConfig sqltoyConfig = ConfigUtil.getConfig("sqltoy", SqltoyConfig.class);
            DataSourceConfig dataSourceConfig = ConfigUtil.getConfig("sqltoy.dataSource", DataSourceConfig.class);
//        DruidDataSource dd;
            DruidDataSource ds = ReflectUtil.newInstance("com.alibaba.druid.pool.DruidDataSource");
//        CopyOptions options = new CopyOptions();
//        options.setEditable(WrapperAdapter.class);
//        BeanUtil.copyProperties(sqltoyConfig, ds, options);
//        BeanUtil.copyProperties(dataSourceConfig, ds, options);
            ds.setUrl(sqltoyConfig.getUrl());
            ds.setUsername(sqltoyConfig.getUsername());
            ds.setPassword(sqltoyConfig.getPassword());
            ds.setDriverClassName(sqltoyConfig.getDriverClassName());

            ds.setInitialSize(dataSourceConfig.getInitialSize());  // 初始连接数
            ds.setMinIdle(dataSourceConfig.getMinIdle());      // 最小空闲连接数
            ds.setMaxActive(dataSourceConfig.getMaxActive());   // 最大连接数
            ds.setMaxWait(dataSourceConfig.getMaxWait());

            ds.init();

            SqlToyContext context = new SqlToyContext();
            context.setDefaultDataSource(ds); // 设置数据源
            context.initialize(); // 初始化 SqlToyContext

            dao = new DefaultLazyDaoImpl(context);
        }catch (Exception e) {
            log.error(e.getMessage() ,e);
        }
    }

    public static <T extends Serializable> Object save(T object) {
        return dao.save(object);
    }
}
